/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-02-17 17:36:44
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 15:57:52
 */
define([
    'static',
    '../../framework/bean/connectionobjects',
    '../../framework/bean/common',
    '../../framework/bean/entrustaccounts',
    '../../framework/bean/adpublishcondition',
    '../../framework/bean/admanage'
], function(
    CONST,
    connectionobjectsModel,
    commonModel,
    entrustaccountsModel,
    adpublishconditionModel,
    admanageModel
) {
    extend(Main, Segment); //继承 保持和 class-instance 分离语言的继承感觉。 放在最上面，因为
    function Main() {
        var _this = this;
        var _super = arguments.callee.parent;
        /**
         ** 初始化页面配置
         **/
        this.init = function() {
            this._DOM = $("[data-seg='setting']"); //当前这个类 hold住的前端引用
            this.$appTree = this._DOM.find('.apps-tree'); //应用tree
            this.$app = this._DOM.find('.apps-select'); //应用
            this.$fbConnectionObjectId = this._DOM.find('input[name=fbConnectionObjectId]');
            this.$platform = this._DOM.find('input[name=platform]');
            this.$status = this._DOM.find('select[name=status]');
            this.$category = this._DOM.find('select[name=category]');
            this.$searchKey = this._DOM.find('input[name=search-key]');
            this.$accounts = this._DOM.find('div[name=accounts]');
            this.$createTimeRangeSince = this._DOM.find('input[name=createTimeRange-since]');
            this.$createTimeRangeUntil = this._DOM.find('input[name=createTimeRange-until]');
            this.$statsTimeRangeSince = this._DOM.find('input[name=statsTimeRange-since]');
            this.$statsTimeRangeUntil = this._DOM.find('input[name=statsTimeRange-until]');
            this.timezoneId = window.sessionStorage.timezoneId + ':00';
            this.timezoneValue = window.sessionStorage.timezoneValue;

            this.children = []; //获得 piece 实例的引用
            _super.init.call(_this);
            this.render();
            this.event();
        };

        this.render = function() {
            commonModel.timestamp(function(date) {
                _this.renderAppTree();
                _this.renderAppAccount([]);
                _this.renderStatus();
                _this.renderSearchKey();
                _this.nowDate = date.date;
                _this.renderCreateTimeRange();
                _this.renderStatsTimeRange();
            });

        }

        this.event = function() {
            // this._DOM.off('click', '.apps-select').on('click', '.apps-select', function(e) {
            //     _this.$appTree.width(_this.$app.width() - 2);
            //     _this.$appTree.toggleClass('hidden');
            // })


            this._DOM.off('click', '.apps-select').on('click', '.apps-select', function(e) {
                _this.$appTree.width(_this.$app.width() - 2);
                _this.$appTree.toggleClass('hidden');
                var triggerEvent = _this.$appTree.hasClass('hidden') ? 'hide' : 'show';
                _this.$appTree.trigger(triggerEvent);
            });
            _this.$appTree.off('show').on('show', function(e) {
                var input = '<span class="select2-search select2-search--dropdown"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox"></span>';
                if ($(this).find('.select2-search').length == 0) {
                    $(this).prepend(input);
                }
                var that = this;
                $(that).find('li.level0').show();
                //让jquery:contains选择器 忽略大小写,只有此处用到.故写到这里
                jQuery.expr[':'].Contains = function(a, i, m) {
                    return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
                };
                jQuery.expr[':'].contains = function(a, i, m) {
                    return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
                };
                $(that).find('input[type="search"]').val('');
                $(that).find('input[type="search"]').off('keyup').on('keyup', function() {
                    var key = $(this).val();
                    if (key.length > 0 && key.trim().length > 0) {
                        $(that).find('li.level0:not(:Contains("' + key + '"))').hide();
                        $(that).find('li.level0:Contains("' + key + '")').show();
                    }else{
                        $(that).find('li.level0').show();
                    }
                })
            });


            this._DOM.off('click', '.btn-query').on('click', '.btn-query', function(e) {
                if ($(this).hasClass('disabled')) {
                    return;
                }
                var clearCurPage = true;
                var params = _this.getParams(clearCurPage);
                if (_this.valicateParams(params)) {
                    $(this).trigger("setting-click", params)
                }
            });
            this._DOM.off('APPLY_CLICK', '.app-accounts').on('APPLY_CLICK', '.app-accounts', function(e) {
                var timezoneArr = [];
                $(this).find('.drop-one-item:not(.all-banner)  input[type=checkbox]:checked').each(function() {
                    var timezone = $(this).parent().data('other');
                    timezoneArr.push(timezone);
                });
                var diff = _.union(timezoneArr);
                if (diff.length > 1) {
                    _this.$accounts.testRemind(I18N.getText('management','diffTimezoneTip'));
                }
                _this._DOM.find('.btn-query').toggleClass('disabled', diff.length > 1);
            });

            this.$category.on('change', $.proxy(this.valicateSearchKey, this));
            this.$searchKey.on('keyup', $.proxy(this.valicateSearchKey, this));
        }

        /**
         * { 渲染应用列表树 }
         *
         * @method     renderAppTree
         */
        this.renderAppTree = function() {
            connectionobjectsModel.searchAppsAndConfigurations(function(apps) {
                var nodes = [];
                _.each(apps, function(app) {

                    app.iconUrl = 'https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p50x50/1939481_681049045315822_8432310770725891036_n.png?oh=070d23f1cf828da0bf064a357742c467&oe=57A7C6DA&__gda__=1469823654_57df7dc74b53a2bf2865907e7f863657';
                    var n = {
                        id: app.id,
                        pId: 0,
                        name: app.name,
                        icon: app.iconUrl,
                        type: 'app', //应用
                        app: app
                    }
                    var children = [];
                    if (app.configurations.length > 0) {
                        _.each(app.configurations, function(conf) {
                            var subN = {
                                id: conf.id,
                                pId: app.id,
                                name: conf.platform,
                                icon: './imgs/icon-market.png',
                                type: 'plat', //平台
                                conf: conf,
                                open : true,
                                app: app
                            }
                            children.push(subN);
                        });
                        n['children'] = children;
                        nodes.push(n);
                    }
                });
                var setting = {
                    view: {
                        dblClickExpand: false,
                        showLine: false
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback: {
                        // beforeExpand: beforeExpand,
                        // onExpand: onExpand,
                        // onCollapse: onCollapse,
                        onClick: _this.selectTreeItem
                    }
                };
                var treeObj = $.fn.zTree.init($(".apps-tree .ztree"), setting, nodes);
                _this.$appTree.addClass('hidden');
            });
        }


        /**
         * { 渲染帐号 }
         *
         * @method     renderAppAccount
         */
        this.renderAppAccount = function(data) {
            console.log(data);
            _this.$accounts.empty().drop({
                type: 4,
                data: data
            });
            if (data.length == 0) {
                _this.$accounts.find('input[name=drop]').val(I18N.getText('management', 'accounts'));
            } else {
                _this.$accounts.find('li.drop-one-item input[type]').prop('checked', true);
                _this.$accounts.find('.btn-default').trigger('click');

            }
        }

        this.renderSearchKey = function() {
            _this._DOM.find('[name="category"]').select2({
                minimumResultsForSearch: Infinity
            })
        }
        this.renderStatus = function() {
            _this._DOM.find('select[name=status]').select2({
                minimumResultsForSearch: Infinity
            });
        }

        /**
         * { 渲染创建时间范围 }
         *
         * @method     renderCreateTimeRange
         */
        this.renderCreateTimeRange = function() {
            var initStart = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(90, 'days');
            var initEnd = moment(_this.nowDate).utcOffset(_this.timezoneValue);
            var config = _this.getDatarangeConfig();
            config.startDate = initStart;
            config.endDate = initEnd;
            _this._DOM.find('.createTimeRange-range').daterangepicker(config, _this.setCreateTimeRange);
            _this.setCreateTimeRange(initStart, initEnd);
            // _this._DOM.find('.createTimeRange-range b.caret').remove();
        }

        this.setCreateTimeRange = function(start, end) {
            var since = start.format("YYYY-MM-DD");
            var until = end.format("YYYY-MM-DD");
            var tpl = '<div>' +
                '<span>' + start.format("YYYY-MM-DD") + I18N.getText('management','to') + end.format("YYYY-MM-DD") + '</span>' +
                '<i class="glyphicon glyphicon-calendar fa fa-calendar pull-right"></i>' +
                '</div>';
            _this.$createTimeRangeSince.val(since + ' 00:00:00')
            _this.$createTimeRangeUntil.val(until + ' 23:59:59')
            _this._DOM.find('.createTimeRange-range').html(tpl);
        }

        /**
         * { 渲染统计数据时间范围 }
         *
         * @method     renderStatsTimeRange
         */
        this.renderStatsTimeRange = function() {
            var initStart = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(0, 'days');
            var initEnd = moment(_this.nowDate).utcOffset(_this.timezoneValue)
            var config = _this.getDatarangeConfig(true);
            config.startDate = initStart;
            config.endDate = initEnd;
            _this.setStatsTimeRange(initStart, initEnd);
            _this._DOM.find('.statsTimeRange-range').daterangepicker(config, _this.setStatsTimeRange);
        }

        this.setStatsTimeRange = function(start, end) {
            var since = start.format("YYYY-MM-DD");
            var until = end.format("YYYY-MM-DD");
            var tpl = '<div>' +
                '<span>' + start.format("YYYY-MM-DD") + I18N.getText('management','to') + end.format("YYYY-MM-DD") + '</span>' +
                '<i class="glyphicon glyphicon-calendar fa fa-calendar pull-right"></i>' +
                '</div>';
            _this.$statsTimeRangeSince.val(since)
            _this.$statsTimeRangeUntil.val(until)
            _this._DOM.find('.statsTimeRange-range').html(tpl);
        }

        /**
         * {  daterangepicker 有一些配置是相同的 }
         *
         * @method     getDatarangeConfig
         * @param      {<type>}  setMinDate  { 是否设置最小日期,统计周期需要设置 }
         * @return     {<type>}  { description_of_the_return_value }
         */
        this.getDatarangeConfig = function(setMinDate) {
            var today = moment(_this.nowDate).utcOffset(_this.timezoneValue),
                yesterday = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(1, 'days'),
                forward_3_day = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(2, 'days'),
                forward_7_day = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(6, 'days'),
                forward_30_day = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(29, 'days'),
                forward_90_day = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(89, 'days'),
                thisMonthBegin = moment(_this.nowDate).utcOffset(_this.timezoneValue).startOf('month'),
                thisMonthEnd = moment(_this.nowDate).utcOffset(_this.timezoneValue).endOf('month'),
                lastMonthBedin = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(1, 'month').startOf('month'),
                lastMonthEnd = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(1, 'month').endOf('month');
            var daysOfWeek = [
                I18N.getText('common', 'date_weekends'),
                I18N.getText('common', 'date_monday'),
                I18N.getText('common', 'date_tuesday'),
                I18N.getText('common', 'date_wednesday'),
                I18N.getText('common', 'date_thursday'),
                I18N.getText('common', 'date_friday'),
                I18N.getText('common', 'date_saturday')
            ];
            var monthNames = [
                I18N.getText('common', 'date_january'),
                I18N.getText('common', 'date_february'),
                I18N.getText('common', 'date_march'),
                I18N.getText('common', 'date_april'),
                I18N.getText('common', 'date_may'),
                I18N.getText('common', 'date_june'),
                I18N.getText('common', 'date_july'),
                I18N.getText('common', 'date_august'),
                I18N.getText('common', 'date_september'),
                I18N.getText('common', 'date_october'),
                I18N.getText('common', 'date_november'),
                I18N.getText('common', 'date_december')
            ];

            var config = {
                timezone: _this.timezoneValue,
                opens: 'left',
                format: 'YYYY-MM-DD',
                maxDate: new Date(_this.nowDate),
                locale: {
                    applyLabel: I18N.getText('management', 'dateApplyLabel'),
                    cancelLabel: I18N.getText('management', 'dateCancelLabel'),
                    fromLabel: I18N.getText('management', 'dateFromLabel'),
                    toLabel: _this.timezoneId,
                    customRangeLabel: I18N.getText('management', 'dateCustomRangeLabel'),
                    daysOfWeek: daysOfWeek,
                    monthNames: monthNames,
                    firstDay: 0
                },
                ranges: {}
            };
            config.ranges[I18N.getText('management', 'dateRanges1')] = [today, today];
            config.ranges[I18N.getText('management', 'dateRanges2')] = [yesterday, today];
            config.ranges[I18N.getText('management', 'dateRanges3')] = [forward_3_day, today];
            config.ranges[I18N.getText('management', 'dateRanges7')] = [forward_7_day, today];

            if (setMinDate) {
                config.minDate = forward_90_day;
            }
            return config;
        }



        /**
         * { 选择了应用 }
         *
         * @method     selectTreeItem
         * @param      {<type>}  e       { description }
         * @param      {<type>}  un      { description }
         * @param      {<type>}  obj     { description }
         */
        this.selectTreeItem = function(e, un, obj) {
            var label = {
                appId: obj.app.fbConnectionObjectId,
                icon: obj.app.iconUrl
            };

            _this.$fbConnectionObjectId.attr('name', obj.app.name);
            _this.$fbConnectionObjectId.attr('iconUrl', obj.app.iconUrl);
            _this.$fbConnectionObjectId.val(obj.app.fbConnectionObjectId)
            if (obj.type && obj.type == 'app') {
                label.name = obj.app.name;
                _this.$platform.val('');
            } else {
                label.name = obj.app.name + ' / ' + obj.conf.platform;
                label.plat = obj.conf.platform;
                _this.$platform.val(obj.conf.platform);
            }
            var tpl = '<img style="margin:10px;width: 16px;height: 16px;" src="' + label.icon + '"> <strong>' + label.name + '</strong>';
            _this.$app.find('.select2-chosen').html(tpl);
            _this.$app.trigger('click');
            var params = {
                connObjId: obj.app.fbConnectionObjectId,
                isOutLink: obj.app.productType == 'outlink'
            }
            admanageModel.getAccounts(params, function(accounts) {
                var data = [];
                _.each(accounts, function(acc) {
                    var v = {
                        val: acc.fbAccountId,
                        text: acc.displayName + "  (" + (acc.timezone ? acc.timezone : "") + "  )",
                        other: acc.offset
                    }
                    data.push(v);
                });
                _this.renderAppAccount(data);
            });
        }

        /**
         * { 获取工具栏除的参数 }
         *
         * @method     getParams
         * @param      {<type>}  e       { 是否清空当前页 }
         */
        this.getParams = function(clearCurPage) {
            var accountIds = [];
            _this.$accounts.find('.drop-list .drop-one-item:not(.all-banner)  input[type=checkbox]:checked').each(function() {
                accountIds.push($(this).val());
            });
            var _returnStatsFields = window.localStorage.getItem("tableHeader").split(",");
            var params = {
                "ecReport" : true,
                "fbConnectionObjectId": _this.$fbConnectionObjectId.val(), // 应用id，即产品id（必须项）
                "fbConnectionObjectName": _this.$fbConnectionObjectId.attr('name'),
                "iconUrl": _this.$fbConnectionObjectId.attr('iconUrl'),
                "accountIds": accountIds, // 账号列表（必须项，至少选择一个账号）
                "adSetStatus": _this.$status.val(), // 广告组状态筛选条件（必须项，可选范围： ACTIVE, PAUSED, DELETED, PENDING_REVIEW, DISAPPROVED, PREAPPROVED, PENDING_BILLING_INFO, CAMPAIGN_PAUSED, ARCHIVED, ADSET_PAUSED ）
                "createTimeRange": {
                    "since": _this.$createTimeRangeSince.val(),
                    "until": _this.$createTimeRangeUntil.val()
                }, // 创建时间筛选条件（必须项，请根据当前登陆用户时区将选择的时间转化为UTC时间即零时区时间，精确到秒，格式请参考示例）
                "statsTimeRange": {
                    "since": _this.$statsTimeRangeSince.val(),
                    "until": _this.$statsTimeRangeUntil.val()
                }, // 统计时间筛选条件（必须项，不需要转换时区，精确到天，格式请参考示例）
                "sort": {
                    "field": "createdUtcTime",
                    "type": -1
                },
                "today": moment(_this.nowDate).utcOffset(_this.timezoneValue).format('YYYY-MM-DD'),
                "returnStatsFields": ["todaySpent","spent","clicks","ctr","cpc","purchase","purchaseR","cps","salesAmount","roi","cart","cartR","gaClicks","gaCart","gaPays","gaOrderAmount","gaCartR","gaCpa","gaCpc","gaOrderPrice","gaRoi","gaCr"]
// 统计数据返回字段，为了避免不必要的网络消耗，对于需要返回的统计数据通过这里指定，取值范围请参考统计数据字段一览（必须项）
            }
            var tempArray = [];
            $.each(params.returnStatsFields,function(i,obj){
                if(-1 != $.inArray(obj,_returnStatsFields)){
                    tempArray.push(obj);
                }
            });
            params.returnStatsFields = tempArray;
            console.log("查询table参数为：");
            console.log(params.returnStatsFields);
            if (_this.$platform.val().length > 0) {
                params.platform = _this.$platform.val(); // 应用平台（可选项，如果未选择平台，该参数可以不传）
            }
            var searchKey = this.$searchKey.val();
            if (searchKey.length > 0) {
                switch (_this.$category.val()) {
                    case 'adName':
                        params.adName = [searchKey];
                        break;
                    case 'adSetName':
                        params.adSetName = [searchKey];
                        break;
                    case 'campaignName':
                        params.campaignName = [searchKey];
                        break;
                    case 'adId':
                        params.adId = searchKey;
                        break;
                    case 'adSetId':
                        params.adSetId = searchKey;
                        break;
                    case 'campaignId':
                        params.campaignId = searchKey;
                        break;
                    default:
                        console.log('no searchKey');
                }
            }

            if (clearCurPage) {
                $('div.ndp-page-wrapper[name="plain-page"]').empty();
            }
            return params;
        }




        /**
         * { 验证 params }
         *
         * @method     valicateParams
         * @param      {<type>}  params  { description }
         */
        this.valicateParams = function(params) {
            if (kit.isBlank(params.fbConnectionObjectId)) {
                _this.$app.testRemind(I18N.getText('management', 'appAndPlatform'));
                return false;
            }
            if (kit.isBlank(params.accountIds)) {
                _this.$accounts.testRemind(I18N.getText('management', 'accounts'));
                return false;
            }
            return true;
        }


        /**
         * { 验证关键字 }
         *
         * @method     valicateSearchKey
         * @param      {<type>}  e       { description }
         */
        this.valicateSearchKey = function(e) {
            var categoryVal = _this.$category.val();
            var searchKeyVal = _this.$searchKey.val();
            if (categoryVal == 'adSetId') {
                var pattern = /^\d+$/;
                if (!pattern.test(searchKeyVal)) {
                    _this.$searchKey.testRemind(I18N.getText('management', 'pleaseInputAdsetId'));
                    _this.$searchKey.val('');
                    _this.$searchKey.focus();
                }
            }
        }

        this.update = function(msg) {
            switch (msg.type) {
                //              case "scroll":
                case "mousemove":
                case "click":
                case "mousewheel":
                    // if (msg.data.h <= 140) {
                    //     this._DOM.css("marginTop", -msg.data.h + "px");
                    // } else {
                    //     this._DOM.css("marginTop", "-140px");
                    // }
                    break;
            }
        }
    }
    return new Main();
});
